package com.li.o2oSystem.web.shopadmin;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.li.o2oSystem.dto.ImageHolder;
import com.li.o2oSystem.dto.ShopExecution;
import com.li.o2oSystem.entity.Area;
import com.li.o2oSystem.entity.PersonInfo;
import com.li.o2oSystem.entity.Shop;
import com.li.o2oSystem.entity.ShopCategory;
import com.li.o2oSystem.enums.ShopStateEnum;
import com.li.o2oSystem.exceptions.ShopOperationException;
import com.li.o2oSystem.service.AreaService;
import com.li.o2oSystem.service.ShopCategoryService;
import com.li.o2oSystem.service.ShopService;
import com.li.o2oSystem.util.CodeUtil;
import com.li.o2oSystem.util.HttpServletRequestUtil;

@Controller //用来标注这是controller的组件
@RequestMapping(value="/shopadmin") 
public class ShopManagementController {
	@Autowired
	private ShopService shopService;
	@Autowired
	private ShopCategoryService shopCategoryService;
	@Autowired
	private AreaService areaService;
	/**
	 * 获取店铺类别信息和区域信息，返回前端
	 * @return
	 */
	@RequestMapping(value="/getshopinitinfo",method=RequestMethod.GET)
	@ResponseBody
	private Map<String,Object> getShopInitInfo(){
		Map<String,Object> modelMap = new HashMap<>();
		List<ShopCategory> shopCategoryList = new ArrayList<>();
		List<Area> areaList = new ArrayList<>();
		try{
			shopCategoryList = shopCategoryService.getShopCategoryList(new ShopCategory());//查询店铺类别列表信息
			areaList = areaService.getAreaList();//区域列表信息
			modelMap.put("shopCategoryList", shopCategoryList);
			modelMap.put("areaList", areaList);
			modelMap.put("success", true);
		}catch(Exception e){
			modelMap.put("success", false);
			modelMap.put("Msg", "获取店铺类别信息异常");
			modelMap.put("errMsg", e.getMessage());
			return modelMap;
		}
		return modelMap;
	}
	/**
	 * 新增店铺信息
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/registershop",method=RequestMethod.POST)//设置映射地址和请求方法
	@ResponseBody//作用是将方法返回的对象转换为json数据
	private Map<String,Object> registerShop(HttpServletRequest request){
		Map<String,Object> modelMap = new HashMap<>();
		//校验验证码
		if(!CodeUtil.checkVerifyCode(request)){//如果验证码不相等
			modelMap.put("success", false);
			modelMap.put("errMsg","验证码错误不正确");
			return modelMap;
		}
		//1、接受并转换相应的参数，包括店铺信息和图片信息
		String shopStr = HttpServletRequestUtil.getString(request, "shopStr");
		ObjectMapper mapper = new ObjectMapper();//ObjectMapper是json库的主要类，将json格式的字符串转化为对象，反之亦然
		Shop shop = null;
		try{
			shop = mapper.readValue(shopStr, Shop.class);//使用json中的ObjectMapper对象，将字符串转化为Java对象
		}catch(Exception e){
			modelMap.put("success", false);
			modelMap.put("errMsg", e.getMessage());
			return modelMap;
		}
		//2、文件流处理
		CommonsMultipartFile shopImg = null;//创建文件流对象
		//文件解析对象
		CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());//从request的本次会话中的上下文去获取相关文件上传的内容
		if(commonsMultipartResolver.isMultipart(request)){//判断request中是否有上传的文件流
			MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
			shopImg = (CommonsMultipartFile) multipartHttpServletRequest.getFile("shopImg");//转化为能够处理的文件流
		}else{//如果没有文件流
			modelMap.put("success", false);
			modelMap.put("errMsg", "上传图片不能为空");
			return modelMap;
		}
		//3、注册店铺
		if(shop != null && shopImg != null){//判断，如果店铺信息和图片流不为空则执行
			PersonInfo owner = (PersonInfo) request.getSession().getAttribute("user");
			shop.setOwner(owner);
			ShopExecution se;
			try {
				ImageHolder imageHolder = new ImageHolder(shopImg.getOriginalFilename(),shopImg.getInputStream());
				se = shopService.addShop(shop, imageHolder);
				if(se.getState() == ShopStateEnum.CHECK.getState()){
					modelMap.put("success", true);
					//该用户可以操作的店铺列表
					@SuppressWarnings("unchecked")//不检查警告
					List<Shop> shopList = (List<Shop>) request.getSession().getAttribute("shopList");
					if(shopList==null || shopList.size() == 0){//如果是初次添加店铺
						shopList = new ArrayList<Shop>();//新建一个店铺列表
					}
					shopList.add(se.getShop());
					request.getSession().setAttribute("shopList", shopList);//将可操作的店铺列表添加进session中
				}else{
					modelMap.put("success", false);
					modelMap.put("errMsg", se.getStateInfo());
					return modelMap;
				}
			} catch (ShopOperationException e) {
				modelMap.put("success", false);
				modelMap.put("errMsg", e.getMessage());
			} catch (IOException e) {
				modelMap.put("success", false);
				modelMap.put("errMsg", e.getMessage());
			}
			return modelMap;
		}else{//如果店铺信息为空或者图片信息为空
			modelMap.put("success", false);
			modelMap.put("errMsg", "请输入店铺信息");
			return modelMap;
		}
	}
	/**
	 * 根据店铺id获取店铺信息
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/getshopbyid",method=RequestMethod.GET)//设置映射地址和请求方法
	@ResponseBody//作用是将方法返回的对象转换为json数据
	private Map<String,Object> getShopById(HttpServletRequest request){
		Map<String,Object> modelMap = new HashMap<>();
		Long shopId = HttpServletRequestUtil.getLong(request, "shopId");
		if(shopId > -1){
			try {
				Shop shop = shopService.getByShopId(shopId);
				List<Area> areaList = areaService.getAreaList();
				modelMap.put("shop", shop);
				modelMap.put("areaList", areaList);
				modelMap.put("success", true);
			} catch (Exception e) {
				modelMap.put("success", false);
				modelMap.put("Msg", "获取店铺信息异常");
				modelMap.put("errMsg", e.getMessage());
			}
		}
		else{
			modelMap.put("success", false);
			modelMap.put("errMsg", "empty shopId");
		}
		return modelMap;
	}
	/**
	 * 修改店铺信息
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unused")
	@RequestMapping(value="/modifyshop",method=RequestMethod.POST)//设置映射地址和请求方法
	@ResponseBody//作用是将方法返回的对象转换为json数据
	private Map<String,Object> modifyShop(HttpServletRequest request){
		Map<String,Object> modelMap = new HashMap<>();
		//校验验证码
		if(!CodeUtil.checkVerifyCode(request)){//如果验证码不相等
			modelMap.put("success", false);
			modelMap.put("errMsg","验证码错误不正确");
			return modelMap;
		}
		//1、接受并转换相应的参数，包括店铺信息和图片信息
		String shopStr = HttpServletRequestUtil.getString(request, "shopStr");
		ObjectMapper mapper = new ObjectMapper();//ObjectMapper是json库的主要类，将json格式的字符串转化为对象，反之亦然
		Shop shop = null;
		try{
			shop = mapper.readValue(shopStr, Shop.class);//使用json中的ObjectMapper对象，将字符串转化为Java对象
		}catch(Exception e){
			modelMap.put("success", false);
			modelMap.put("errMsg", e.getMessage());
			return modelMap;
		}
		//2、文件流处理
		CommonsMultipartFile shopImg = null;//创建文件流对象
		//文件解析对象
		CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());//从request的本次会话中的上下文去获取相关文件上传的内容
		if(commonsMultipartResolver.isMultipart(request)){//判断request中是否有上传的文件流
			MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
			shopImg = (CommonsMultipartFile) multipartHttpServletRequest.getFile("shopImg");//转化为能够处理的文件流
		}
		//3、修改店铺信息
		if(shop != null && shop.getShopId() != null){
			ShopExecution se;
			try {
				ImageHolder imageHolder = new ImageHolder(shopImg.getOriginalFilename(),shopImg.getInputStream());
				if(shopImg == null){//如果图片为空，则不处理图片
					se = shopService.modifyShop(shop, null);
				}
				else{
					se = shopService.modifyShop(shop, imageHolder);
				}
				if(se.getState() == ShopStateEnum.SUCCESS.getState()){
					modelMap.put("success", true);
				}else{
					modelMap.put("success", false);
					modelMap.put("errMsg", se.getStateInfo());
					return modelMap;
				}
			} catch (ShopOperationException e) {
				modelMap.put("success", false);
				modelMap.put("errMsg", e.getMessage());
			} catch (IOException e) {
				modelMap.put("success", false);
				modelMap.put("errMsg", e.getMessage());
			}
			return modelMap;
		}else{//如果店铺信息为空或者图片信息为空
			modelMap.put("success", false);
			modelMap.put("errMsg", "请输入店铺id");
			return modelMap;
		}
	}
	/**
	 * 分页查询店铺信息列表
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/getshoplist",method=RequestMethod.GET)//设置映射地址和请求方法
	@ResponseBody //作用是将方法返回的对象转换为json数据
	private Map<String,Object> getShopList(HttpServletRequest request){
		Map<String,Object> modelMap = new HashMap<>();
		PersonInfo user;
		//user.setUserId(1L);//给UserId设置一个默认值
		//user.setName("张三");
		//request.getSession().setAttribute("user",user);//将用户设置进session中
		user = (PersonInfo) request.getSession().getAttribute("user");//在session中获取userId
		try {
			Shop shopCondition = new Shop();
			shopCondition.setOwner(user);//设置店铺的用户信息
			ShopExecution se = shopService.getShopList(shopCondition, 0, 100);//设置默认页码和页数
			modelMap.put("shopList", se.getShopList());
			//返回店铺列表成功后，将列表作为权限验证，放入session中
			request.getSession().setAttribute("shopList", se.getShopList());
			modelMap.put("user", user);
			modelMap.put("success", true);
			return modelMap;
		} catch (Exception e) {
			modelMap.put("success", false);
			modelMap.put("errMsg", e.getMessage());
			return modelMap;
		}
	}
	/**
	 * 店铺列表管理
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/getshopmanagementinfo",method=RequestMethod.GET)//设置映射地址和请求方法
	@ResponseBody//作用是将方法返回的对象转换为json数据
	private Map<String,Object> getShopManagementInfo(HttpServletRequest request){
		Map<String,Object> modelMap = new HashMap<>();
		long shopId = HttpServletRequestUtil.getLong(request, "shopId");//获取请求中的shopId
		if(shopId <= 0){
			Object currentShopObj = request.getSession().getAttribute("currentShop");//获取存入session中的当前店铺
			if(currentShopObj == null){//如果当前店铺仍旧为空
				modelMap.put("redirect", true);//重定向为true
				modelMap.put("url", "/o2oSystem/shopadmin/shoplist");
			}else{
				Shop currentShop = (Shop) currentShopObj;//强制将从request中获取的对象装换为Shop对象
				modelMap.put("redirect", false);
				modelMap.put("shopId", currentShop.getShopId());//返回当前店铺的id
			}
		}else{ // 店铺id不小于0
			Shop currentShop = new Shop();
			currentShop.setShopId(shopId);//设置当前店铺的id
			request.getSession().setAttribute("currentShop", currentShop);//将当前店铺信息设置进session中
			modelMap.put("redirect", false);//不需要重定向
		}
		return modelMap;
	}
}

